/*=========================================================================
 *
 *  Copyright Arash Akbarinia
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

/**
* @file FolderIo.cpp
*
*/

#include "laperconfig.h"
#include "io.h"

#include <algorithm>
#include <dirent.h>

void laper::io::ReadFilesOfDirectory ( const std::string& DirectoryName, std::vector< std::string >& FileNames, const std::vector< std::string >& FileExtensions, const bool AddDirectoryName )
{
  FileNames.clear();

  DIR* dir = opendir ( DirectoryName.c_str() );
  FILE_LOG ( logDEBUG ) << "openning directory " << DirectoryName;
  if ( dir != NULL )
    {
      struct dirent* dent;
      while ( ( dent = readdir ( dir ) ) != NULL )
        {
          std::string curfilename = std::string ( dent->d_name );
          // FIXME: fix the empty vector
          for ( unsigned int i = 0; i < FileExtensions.size(); i++ )
            {
              // TODO: support upper and lower cases.
              if ( std::string::npos != curfilename.find ( FileExtensions[i].c_str() ) /*|| std::string::npos == curfilename.find ( FileExtensions[i].c_str() )*/ )
                {
                  FILE_LOG ( logDEBUG ) << "file " << curfilename << " added to the list";
                  if ( AddDirectoryName )
                    {
                      FileNames.push_back ( DirectoryName + "/" + curfilename );
                    }
                  else
                    {
                      FileNames.push_back ( curfilename );
                    }
                }
            }
        }
    }

  std::sort ( FileNames.begin(), FileNames.end() );
}
